<template>
  <div id="incityOrderDetail" ref="incitybottombox">
    <div class="sharecover" v-show="Issharecover" @click="sharecoverBtn" :style="Height"></div>
    <!--二维码分享-->
    <div class="code_box" v-show="Iscodebox">
      <div ref="qrcode" class="qrcode"></div>
      <p class="qrcode_text">长按二维码进行分享</p>
    </div>
    <!--微信分享-->
    <div v-show="Issharebox" class="share_box">
      <img src="@/assets/imgs/share_right.png" />
      <p>点击右上角按钮发送给微信好友或分享到微信朋友圈</p>
    </div>
    <incity-map ref="map" class="map"></incity-map>
    <div class="top_bar">
      <p>
        <md-icon class="back_btn" name="snyc_nav_fh" @click="goIncityBack()"></md-icon>
      </p>
    </div>
    <order-bottom
      :orderStatusShow="orderStatusShow"
      ref="orderBottom"
      @orderCancel="onOrderCancel"
      @dingweiBtn="dingweiBtn"
      @evaluated="evaluated"
      @incityShareBtn="incityShareBtn"
    ></order-bottom>
  </div>
</template>
<script>
import '@/assets/svgs/snyc_nav_fh.svg';
import IncityMap from './IncityMap';
import OrderBottom from './components/OrderBottom';
import { GET_CURRENT_LOCATION } from '@/store/actions.types';
import { mapGetters, mapActions, mapMutations } from 'vuex';
import { decryptByDESModeEBC, encryptByDESModeEBC } from '@/common/encrypt';
import { Dialog, Icon } from 'mand-mobile';
import QRCode from 'qrcodejs2';
import TopBar from '@/components/TopBar';
import weixinUtils from '@/common/weixinUtils';
import Utils from '@/common/pakjUtils';
import XBack from 'xback';
import http from '@/common/http';
import Loading from '@/components/loading';
export default {
  name: 'incity-order-detail',
  components: {
    [IncityMap.name]: IncityMap,
    [OrderBottom.name]: OrderBottom,
    [Icon.name]: Icon,
    [TopBar.name]: TopBar
  },
  data() {
    return {
      title: '订单详情',
      Height: {
        height: ''
      },
      orderStatusShow: 0,
      mqttInited: false,
      orderTopicSubscribed: false,
      gpsTopicSubscribed: false,
      Iscodebox: false,
      Issharebox: false,
      Issharecover: false,
      qrcode: ''
    };
  },
  created() {
    this.getCityOrderDetail(true);
    this.xBack = XBack.init(window, event => {
      this.goIncityBack();
      this.xBack.uninit();
    });
  },
  methods: {
    goIncityBack() {
      Loading.hide();
      this.$store.commit('resetIncity');
      this.$router.replace({
        name: 'MyAllot'
      });
    },
    ...mapActions(['getIncityOrderInfo']),
    getCityOrderDetail(mqtt) {
      // 获取订单详情
      if (this.$route.query.orderno) {
        let param = {
          orderNo: this.$route.query.orderno
        };
        this.getIncityOrderInfo(param).then(() => {
          console.log(this.getIncityOrderDate);
          this.init(mqtt);
        });
      } else {
        Dialog.alert({
          title: '提示',
          content: '获取不到订单号',
          confirmText: '确定'
        });
      }
    },
    init(mqtt = false) {
      if (this.getIncityOrderDate.orderStatus === '1') {
        // 待抢单
        this.orderStatusShow = 0;
        if (mqtt) {
          this.initMqtt().then(() => {
            this.subscribeOrderTopic();
          });
        }
        this.$refs.map.clearMap();
        this.$refs.map.showStartEndPosition(this.incityOrderStartPositionInfo, this.incityOrderEndPositionInfo);
        if (this.incityOrderNearDriverFlag) {
          this.$refs.map.createTextTip(this.incityOrderStartPositionInfo.coordinate, '正在为您寻找车辆');
        } else {
          this.$refs.map.createTextTip(this.incityOrderStartPositionInfo.coordinate, '附近暂时没有车辆');
        }

        this.$store.dispatch(GET_CURRENT_LOCATION).then(() => {
          this.$refs.map.addDingweiMarker(this.getCurrentLocation.coordinate);
        });
      } else if (this.getIncityOrderDate.orderStatus === '2') {
        // 接驾中
        this.orderStatusShow = 1;
        if (mqtt) {
          this.initMqtt().then(() => {
            this.subscribeOrderTopic();
            this.subscribeGpsTopic();
          });
        }
        this.$refs.map.clearMap();
        this.$refs.map.addCountdownTip(
          this.incityOrderStartPositionInfo.coordinate,
          '请在倒计时结束前走到该站点',
          this.getIncityOrderDate.expectDriverDate
        );
        this.$store.dispatch('getIncityOrderWayPath', this.$route.query.orderno).then(() => {
          this.$refs.map.showIncityOrderWayPath(this.incityDriverPositionByAPI, this.incityOrderWayPath).then(() => {
            this.$refs.map.updateDriveCar(this.incityDriverPositionByAPI);
            this.$refs.map.setFitView();
          });
        });
        this.$store.dispatch(GET_CURRENT_LOCATION).then(() => {
          this.$refs.map.addDingweiMarker(this.getCurrentLocation.coordinate);
        });
      } else if (this.getIncityOrderDate.orderStatus === '3') {
        // 司机已到达
        this.orderStatusShow = 1;
        if (mqtt) {
          this.initMqtt().then(() => {
            this.subscribeOrderTopic();
            this.subscribeGpsTopic();
          });
        }
        this.$refs.map.clearMap();
        this.$refs.map.updateDriveCar(this.incityDriverPositionByAPI);
        this.$refs.map.addStartMarker(
          this.incityOrderStartPositionInfo.coordinate,
          this.incityOrderStartPositionInfo.stationName
        );
        this.$refs.map.addCountdownTip(
          this.incityOrderStartPositionInfo.coordinate,
          '内上车，司机已到达',
          this.getIncityOrderDate.waitUserToDate
        );
        this.$refs.map.setFitView();
        this.$store.dispatch(GET_CURRENT_LOCATION).then(() => {
          this.$refs.map.addDingweiMarker(this.getCurrentLocation.coordinate);
        });
      } else if (this.getIncityOrderDate.orderStatus === '4') {
        // 行程中
        this.orderStatusShow = 1;
        if (mqtt) {
          this.initMqtt().then(() => {
            this.subscribeOrderTopic();
            this.subscribeGpsTopic();
          });
        }
        this.$refs.map.clearMap();
        this.$store.dispatch('getIncityOrderWayPath', this.$route.query.orderno).then(() => {
          this.$refs.map.showIncityOrderWayPath(this.incityDriverPositionByAPI, this.incityOrderWayPath).then(routeInfo => {
            console.log('当前规划的线路信息：', routeInfo);
            this.$refs.map.addIncityTravellingTip(this.incityDriverPositionByAPI, routeInfo.distance, routeInfo.time);
            this.$refs.map.updateDriveCar(this.incityDriverPositionByAPI);
            this.$refs.map.setFitView();
          });
        });
      } else if (this.getIncityOrderDate.orderStatus === '5') {
        // 已完成
        this.orderStatusShow = 4;
        //  评价拉起状态 0未弹出 1弹出
        if (this.getIncityOrderDate.evaluateShow === '0') {
          this.$refs.orderBottom.goEvaluate();
        }
        this.closeMqtt();
        this.$refs.map.clearMap();
        this.$refs.map.addIncityFinishTip(this.incityOrderEndPositionInfo.coordinate, this.getIncityOrderDate.distance);
        this.$refs.map.showStartEndPosition(this.incityOrderStartPositionInfo, this.incityOrderEndPositionInfo);
      } else if (this.getIncityOrderDate.orderStatus === '6') {
        // 已取消
        this.orderStatusShow = 2;
        this.closeMqtt();
        this.$refs.map.clearMap();
        this.$refs.map.showStartEndPosition(this.incityOrderStartPositionInfo, this.incityOrderEndPositionInfo);
      } else if (this.getIncityOrderDate.orderStatus === '7') {
        // 已关闭
        this.orderStatusShow = 3;
        this.closeMqtt();
        this.$refs.map.clearMap();
        this.$refs.map.showStartEndPosition(this.incityOrderStartPositionInfo, this.incityOrderEndPositionInfo);
      }
      this.$refs.orderBottom.orderInit();
    },
    async initMqtt() {
      if (this.mqttClient) {
        if (this.mqttConnected) {
          throw new Error('MQTT已经连接了');
        }
      }
      await this.$store.dispatch('getMqttConfig');
      console.log(this.mqttConfig);
      await this.$store.dispatch('initMqttClient', this.mqttConfig);
      // 链接MQTT
      this.mqttInited = true;
      this.mqttClient.onMessageArrived = this.onMessageArrive;
      this.mqttClient.onConnectionLost = this.onMqttLost;
      return;
    },
    subscribeOrderTopic() {
      if (this.orderTopicSubscribed || this.incityincityOrderTopic === '') {
        return;
      }
      if (this.mqttInited) {
        this.$store.dispatch('subscribe', this.incityOrderTopic).then(() => {
          this.orderTopicSubscribed = true;
        });
      }
    },
    subscribeGpsTopic() {
      if (this.gpsTopicSubscribed || this.incityDriverTopic === '') {
        return;
      }
      if (this.mqttInited) {
        this.$store.dispatch('subscribe', this.incityDriverTopic).then(() => {
          this.gpsTopicSubscribed = true;
        });
      }
    },
    onMqttLost(response) {
      this.mqttInited = false;
      console.error('MQTT连接丢失，这有可能是消息内部处理出错!');
    },
    onMessageArrive(message) {
      let str = message.payloadString;
      if (message.topic === this.incityOrderTopic) {
        // 更新订单状态
        let result = JSON.parse(str);
        console.log('市内用车：订单状态更新：', result);
        this.getCityOrderDetail(false);
      } else if (message.topic === this.incityDriverTopic) {
        // 更新司机位置
        let jsonstr = decryptByDESModeEBC(str);
        let result = JSON.parse(jsonstr);
        console.log('接收到MQTT司机位置消息：', result);
        if (result.position) {
          let positionStr = decryptByDESModeEBC(result.position);
          this.$store.commit('setCurrentGpsPosition', positionStr);
        }
      }
    },
    onOrderCancel() {
      this.closeMqtt();
    },
    closeMqtt() {
      if (this.gpsTopicSubscribed) {
        this.gpsTopicSubscribed = false;
        this.$store.dispatch('unsubscribe', this.incityDriverTopic);
      }
      if (this.orderTopicSubscribed) {
        this.orderTopicSubscribed = false;
        this.$store.dispatch('unsubscribe', this.incityOrderTopic);
      }
      if (this.mqttConnected) {
        this.$store.commit('closeMqtt');
        this.mqttInited = false;
      }
    },
    dingweiBtn() {
      console.log('获取当前位置');
      this.$refs.map.setFitView();
    },
    evaluated() {
      this.getCityOrderDetail(false);
    },
    getheight() {
      this.Height.height = this.$refs.incitybottombox.clientHeight + 'px';
    },
    sharecoverBtn() {
      this.Issharecover = false;
      this.Iscodebox = false;
      this.Issharebox = false;
    },
    // 分享行程
    incityShareBtn() {
      this.getheight();
      this.Issharecover = true;
      this.getshareTrip();
    },
    getshareTrip() {
      let params = {
        order_no: this.$route.query.orderno,
        type: '3'
      };
      Loading.show();
      http.post('/pakj/order/getShareOrderUrl', params).then(res => {
        Loading.hide();
        if (res.data.code === '000000') {
          console.log(res.data);
          this.shareTripUrl = res.data.data.shareUrl;
          this.getshareConfig(res.data.data.shareUrl, res.data.data.shareTitle, res.data.data.shareDesc);
          // 判断是微信还是h5中
          if (Utils.isWeixinBroswer()) {
            //  微信中
            this.Issharebox = true;
          } else {
            this.Iscodebox = true;
            if (!this.qrcode) {
              this.qrcode = new QRCode(this.$refs.qrcode, {
                width: 120,
                height: 120, // 高度
                text: this.shareTripUrl // 二维码链接
              });
            }
          }
        } else {
          Dialog.alert({
            title: '提示',
            content: res.data.msg,
            confirmText: '确定'
          });
        }
      });
    },
    getshareConfig(shareUrl, shareTitle, shareDesc) {
      weixinUtils
        .wxConfig([
          'onMenuShareTimeline', // 分享到朋友圈接口
          'onMenuShareAppMessage', //  分享到朋友接口
          'onMenuShareQQ', // 分享到QQ接口
          'onMenuShareQZone', // 分享到qq空间
          'onMenuShareWeibo' // 分享到微博接口
          // 'updateAppMessageShareData', // 分享给朋友及分享到QQ
          // 'updateTimelineShareData ' // 分享到朋友圈及分享到QQ空间
        ])
        .then(() => {
          let shareData = {
            imgUrl: 'https://img.padj.group/pakj_logo.png', // 分享显示的缩略图地址
            link: shareUrl, // 分享地址
            desc: shareTitle, // 分享描述
            title: shareDesc, // 分享标题
            success: () => {
              // Toast({
              //     icon: 'circle-right',
              //     content: '分享成功',
              //     position: 'bottom'
              // });
              this.sharecoverBtn();
            }
          };
          wx.onMenuShareTimeline(shareData);
          wx.onMenuShareAppMessage(shareData);
          wx.onMenuShareQQ(shareData);
          wx.onMenuShareQZone(shareData);
          wx.onMenuShareWeibo(shareData);
        })
        .catch(reason => {
          // config信息验证失败会执行error函数，如签名过期导致验证失败
          // 具体错误信息可以打开config的debug模式查看，也可以在返回的res参数中查看
          // 对于SPA可以在这里更新签名
          alert('好像出错了');
        });
    }
  },
  watch: {
    currentGpsPosition(newVal) {
      console.log('司机位置更新 ：', newVal);
      if (this.$refs.map) {
        let pos = newVal.split(',');
        this.$refs.map.updateDriveCar(pos);
        if (this.incityOrderWayPath) {
          this.$refs.map.updateIncityTravellingTip(pos, this.incityOrderWayPath);
        }
      }
    }
  },
  computed: {
    ...mapGetters([
      'getCurrentLocation',
      'getIncityOrderDate',
      'mqttConfig',
      'mqttClient',
      'mqttConnected',
      'incityDriverTopic',
      'incityOrderTopic',
      'incityOrderStartPositionInfo',
      'incityOrderEndPositionInfo',
      'incityOrderMiddleWayPathCoordinate',
      'incityDriverPositionByAPI',
      'incityOrderWayPath',
      'currentGpsPosition',
      'incityOrderNearDriverFlag'
    ])
  }
};
</script>
<style lang="stylus" scoped>
#incityOrderDetail {
  .map {
    height: 100vh;
  }

  .top_bar {
    position: absolute;
    top: 0px;
    z-index: 1000;
    width: 100%;
  }

  .top_bar p {
    height: 88px;
    line-height: 88px;
    padding: 0px 30px;
  }

  .back_btn {
    width: 22px;
    height: 38px;
  }

  .sharecover {
    position: absolute;
    width: 100%;
    height: 100vh;
    top: 0px;
    background-color: #000;
    opacity: 0.5;
    z-index: 9999;
  }

  .code_box {
    position: absolute;
    z-index: 10000;
    top: 35%;
    left: 35%;
  }

  .qrcode_text {
    font-size: 28px;
    color: #fff;
    marign-top: 20px;
  }

  .share_box {
    position: absolute;
    z-index: 10000;
    right: 2%;
    font-size: 28px;
    color: #fff;
    width: 240px;
  }

  .share_box img {
    width: 120px;
    position: relative;
    left: 100px;
  }

  .share_box p {
    margin-top: 10px;
  }
}
</style>
